<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      var pathSum = function (root, targetSum) {
        if (!root) return []
        let result = []
        function preOrder(root, path) {
          if (!root.left && !root.right) {
            let sum = path.reduce((pre, item) => (pre += item))
            if (sum == targetSum) {
              return result.push([...path])
            }
          }
          if (root.left) {
            path.push(root.left.val)
            preOrder(root.left, path)
            path.pop()
          }
          if (root.right) {
            path.push(root.right.val)
            preOrder(root.right, path)
            path.pop()
          }
        }
        preOrder(root, [root.val])
        return result
      }
    </script>
  </body>
</html>
